package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 增加菜品分类
     * @param category
     * @return
     */
    @PostMapping
    public R save(@RequestBody Category category){
        log.info("添加菜品分类:"+category);
        boolean b = categoryService.save(category);
        return b?R.success("成功"):R.error("失败");
    }

    /**
     * 菜品分类分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize){
        log.info("分类的page查询: page "+page+" pageSize "+pageSize);
        //设置分页
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //查询  排序  先按照分类类型排序  再按照 排序权重排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getType,Category::getSort);
        categoryService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改菜品分类
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        log.info("修改菜品分类->"+category);
        //修改
        boolean b = categoryService.updateById(category);
        return b?R.success("成功"):R.error("失败");
    }

    /**
     * 删除菜品分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R delete(Long id){
        log.info("删除菜品分类:"+id);
//        boolean b = categoryService.removeById(id);
        boolean b = categoryService.delete(id);
        return b?R.success("成功"):R.error("失败");
    }

    /**
     * 获取分类列表
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R getList(Integer type){
        log.info("获取分类列表"+type);
        //设置查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type!=null,Category::getType,type)
        //添加排序条件
                .orderByDesc(Category::getType).orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

}
